package com.qf.smsplatform.gateway.netty4;

import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.gateway.mq.MTQueue;
import com.qf.smsplatform.gateway.mq.StatQueue;
import com.qf.smsplatform.gateway.netty4.Utils.MsgUtils;
import com.qf.smsplatform.gateway.netty4.entity.CmppDeliver;
import com.qf.smsplatform.gateway.netty4.entity.CmppSubmitResp;
import com.qf.smsplatform.gateway.netty4.entity.ControlWindow;
import com.qf.smsplatform.gateway.netty4.entity.ReportMatch;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 主要业务 handler
 * @author weixiang
 * @date 2018/8/2 15:37
 */

public class CMPPHandler extends SimpleChannelInboundHandler {
    private final static Logger log = LoggerFactory.getLogger(CMPPHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 第一次回调
        if (msg instanceof CmppSubmitResp){
            //  确定是第一次回调后，将msg强转为CmppSubmitResp
            CmppSubmitResp resp=(CmppSubmitResp)msg;

            // 获取到临时存储的submit对象
            ControlWindow controlWindow = ControlWindow.getInstance();
            StandardSubmit submit = (StandardSubmit)controlWindow.remove(resp.getMsgId());
            // 设置运营商返回的msgid
            submit.setMsgid(String.valueOf(resp.getMsgId2()));


            // 再次将设置好msgid的submit对象存储到了一个hashMap中， 以submit对象中的msgid属性作为key
            ReportMatch reportMatch = ReportMatch.getInstance();
            reportMatch.put(resp.getMsgId2(),submit);

            // 将submit扔到队列中
            MTQueue mtQueue = MTQueue.getInstance();
            mtQueue.add(submit);
        }


        // 第二次回调
        if (msg instanceof CmppDeliver){
            CmppDeliver resp=(CmppDeliver)msg;
            // 是否为状态报告 0：非状态报告1：状态报告
            if (resp.getRegistered_Delivery() == 1) {
                // 如果是状态报告的话
                StatQueue statQueue = StatQueue.getInstance();
                statQueue.add(msg);
            } else {
                //用户回复会打印在这里
                log.info(""+ MsgUtils.bytesToLong(resp.getMsg_Id()));
                log.info(resp.getSrc_terminal_Id());
                log.info(resp.getMsg_Content());
            }
        }
    }

}
